package com.echo.blog.business.api;

import com.echo.blog.business.sys.model.SysUser;
import com.echo.blog.business.sys.service.ISysUserService;
import com.echo.blog.core.utils.FastDFSUtils;
import com.echo.model.constant.response.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @version: V1.0
 * @author: chentailai
 * @className: FastDFSApi
 * @packageName: com.echo.blog.business.api
 * @description: 与文件系统交互的api
 * @data: 2020/4/13 12:48
 **/
@Slf4j
@RequestMapping("/file")
@RestController
public class FastDFSApi {

    @Resource
    private ISysUserService sysUserService;

    @Value("${file.dfsPath}")
    public String FILE_URL;

    /**
     * @Author chentailai
     * @Description 上传文件到FastDFS
     * @Param [file]
     * @Return void
     * @Date 2020/4/13 12:50
     */
    @RequestMapping(value = "/fastDFSUpload", method = RequestMethod.POST)
    public ResponseData fastDFSUpload(@RequestParam(value = "image", required = false) MultipartFile file, @RequestParam(value = "id", required = false) Integer id) {
        if (file == null) {
            return ResponseData.error("文件对象不能为空");
        }
        //文件名
        String file_name = file.getOriginalFilename();
        //文件大小
        long file_Size = file.getSize();
        byte[] bytes = null;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            log.error("获取文件字节流失败", e);
        }

        String avatar_path = FILE_URL + FastDFSUtils.uploadPic(bytes, file_name, file_Size);
        log.info("文件路径为:{}", avatar_path);
        //更新用户的头像
        if (id != null) {
            SysUser sysUser = new SysUser();
            sysUser.setId(id);
            sysUser.setAvatar(avatar_path);
            sysUserService.updateById(sysUser);
            log.info("id为:{} 的用户，头像已更新，新头像的地址为:{}", id, avatar_path);
        }

        return ResponseData.success(200, "上传图片成功", avatar_path);
    }
}
